package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

//表格信息
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    /**
     * 查询过去12个月的会员人数情况
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        //获取当前日期对象
        Calendar calendar = Calendar.getInstance();
        //获取12个月之前的日期
        calendar.add(Calendar.MONTH,-12);//用当前日期会推12个月得到
        //遍历出这12个日期
        List<String> months=new ArrayList<>();
        for (int i = 0; i <12; i++) {
            calendar.add(Calendar.MONTH,1);//获得的日期往后推一个月
            Date date = calendar.getTime();
            //将遍历出的日期转化名为年和月的格式，并添加到日期的list集合中
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }

        //调用service服务根据日期查询会员人数
        List<Integer> memberCount= memberService.findMemberCountByMonths(months);
        //使用map集合封装日期和人数的list，是以为页面需要的数据格式如下
        //:{        "months":["2019.01","2019.02","2019.03","2019.04"],
        //              "memberCount":[3,4,8,10]           },
        Map<String,Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
    //套餐预约情况，饼状图的信息
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //页面需要的信息：
        //{    "data":{
        //              "setmealNames":["套餐1","套餐2","套餐3"],
        //              "setmealCount":[
        //              {"name":"套餐1","value":10},
        //              {"name":"套餐2","value":30},
        //              {"name":"套餐3","value":25}                          
        //              ]          
        //              },    "
        //              flag":true,    "
        //              message":"获取套餐统计数据成功"
        //              }
        //data部分需要用一个map来封装两个list数组来实现
        Map<String,Object> data = new HashMap<>();
        //套餐名称的数组setmealNames":["套餐1","套餐2","套餐3"],
        List<String> setmealNames =new ArrayList<>();

        try {
            //调用service查询出套餐名称和预约数,需要用list数组中存储map集合来实现
            List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");//获取套餐名称
                setmealNames.add(name);//为setmealNames添加数据
            }
            data.put("setmealNames",setmealNames);
            data.put("setmealCount",setmealCount);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
    //运营数据查询Controller
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        //需要返回到页面的json格式数据为
        /*{  "data":{    
                        "todayVisitsNumber":0,    
                        "reportDate":"2019-04-25",    
                        "todayNewMember":0,    
                        "thisWeekVisitsNumber":0,    
                        "thisMonthNewMember":2,    
                        "thisWeekNewMember":0,    
                        "totalMember":10,    
                        "thisMonthOrderNumber":2,    
                        "thisMonthVisitsNumber":0,    
                        "todayOrderNumber":0,    
                        "thisWeekOrderNumber":0,    
                        "hotSetmeal":[    
                        {"proportion":0.4545,"name":"粉红珍爱(女)升级TM12项筛查体检套 餐","setmeal_count":5},    
                        {"proportion":0.1818,"name":"阳光爸妈升级肿瘤12项筛查体检套 餐","setmeal_count":2},    
                        {"proportion":0.1818,"name":"珍爱高端升级肿瘤12项筛查","setmeal_count":2},    
                        {"proportion":0.0909,"name":"孕前检查套餐","setmeal_count":1}  
                        ],
                        },  
                        "flag":true,  
                        "message":"获取运营统计数据成功"
                        }

         * */
        //为了满足前台页面要求，所以使用map封装数据
        try {
            Map<String,Object> data = reportService.getBusinessReport();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    //导出运营数据，excel文件
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request,HttpServletResponse response){
        try {
            //查询运营数据
            Map<String,Object> result = reportService.getBusinessReport();
            //分别取出每一个数据，用于添加到excel表格中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            //热门套餐信息
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //通过request获取给定的excel摸板文件的真实路径
            String templateRealPath= request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";
            //读取摸板文件，创建相同的excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            //获取excel工作簿中的第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取第三行第六个单元格，向里面存入日期信息
            XSSFRow row = sheet.getRow(2); //获取第三行，索引由0开始所以参数是2
            XSSFCell cell = row.getCell(5);//获取第6个单元格
            cell.setCellValue(reportDate); //赋值，将日期存入日期单元格

            //获取5行第6个和第7个单元格，存入相应数据
            row = sheet.getRow(4);
            cell=row.getCell(5);
            cell.setCellValue(todayNewMember);//赋值
            cell=row.getCell(7);
            cell.setCellValue(totalMember);//总会员数赋值

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum=12;
            //遍历热门套餐的list集合
            for (Map map : hotSetmeal) {
                //获取每隔热门套餐的信息
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                //为第13行以及13行后面的各行的每个单元格赋值
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//预约占比
            }
            //响应输出流，提供浏览器进行文件下载
            //因为要以浏览器为客户端下载，所以不能直接new OutputStream
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应文件类型为excel类型
            response.setContentType("application/vnd.ms-excel");
            //设置头信息，以附件形式下载，而不是在浏览器打开
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(outputStream);
            //刷新
            outputStream.flush();
            //关闭流
            outputStream.close();
            //关闭工作簿
            workbook.close();
            return null;//不需要向前台返回数据

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL,null);
        }
    }
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response) throws Exception{
        try {
            //查询运营数据
            Map<String,Object> result = reportService.getBusinessReport();

            //热门套餐信息
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //jrxml摸板路径
            String jrxmlPath =request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business3.jrxml";
            //设置根据jrxl摸板生成的jasper文件的目录
            String jasperPath =request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business3.jasper";
            //编译摸板
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

            //使用javaBean方式为摸板设置数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));
            //通过response获得输出流，输出Pdf文件到浏览器，提供下载
            ServletOutputStream out = response.getOutputStream();
            //设置响应文件类型为excel类型
            response.setContentType("application/pdf");
            //设置头信息，以附件形式下载，而不是在浏览器打开
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            //刷新
            out.flush();
            //关闭流
            out.close();
            //输出PDF文件
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
